/*
 * #%L
 * SwiftUIWeb Maven Webapp
 * $Id:$
 * $HeadURL:$
 * %%
 * Copyright (C) 2011 - 2012 Linkwithweb
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public 
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
/**
 * 
 */
package com.linkwithweb.products.swiftui.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.linkwithweb.products.swiftui.context.SystemContext;

/**
 * @author ashwin kumar
 * 
 */
@Controller
public class FileDownloadController extends AbstractController {
	private static final transient Log logger = LogFactory.getLog(FileDownloadController.class);

	/**
	 * @param fileType
	 * @param fileName
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/download/{file_type}/{file_name}", method = RequestMethod.GET)
	public void getFile(@PathVariable("file_type") String fileType, @PathVariable("file_name") String fileName,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			File destinationDir = null;

			String basePath = System.getProperty("user.dir");
			if (StringUtils.equalsIgnoreCase(fileType, "TEMPLATE")) {
				destinationDir = new File(basePath + "/customuploads/");
				fileName = fileName + ".xls";
			}else if (StringUtils.equalsIgnoreCase(fileType, "BACKUP")) {
				String userHome = System.getProperty("user.home");
				String backupDirectory = userHome + "/.swiftui/framework/backups/"
						+ SystemContext.getInstance().getUserContext().getIdentifier() + "/";
				destinationDir = new File(backupDirectory);
				fileName = fileName.replaceAll("-", "").replaceAll(" ", "").replaceAll(":", "")+"_backup" + ".sql";
			} else {
				destinationDir = new File(basePath + "/fileuploads/");
				fileName = fileName + ".xls";
			}

			File file = new File(destinationDir, fileName);

			String mimetype = null;

			// sets response content type
			/*
			 * if (mimetype == null) {
			 * mimetype = "application/octet-stream";
			 * }
			 * response.setContentType(mimetype);
			 * response.setContentLength((int) file.length());
			 */

			// sets HTTP header
			response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

			byte[] byteBuffer = new byte[256];
			FileInputStream fis = new FileInputStream(file);

			int length;
			// reads the file's bytes and writes them to the response stream
			while ((length = fis.read(byteBuffer)) != -1) {
				response.getOutputStream().write(byteBuffer, 0, length);
			}

			fis.close();

			// response.setContentType("text/plain");

			// response.setContentType("application/octet-stream");
			response.flushBuffer();
		} catch (IOException ex) {
			logger.info("Error writing file to output stream. Filename was '" + fileName + "'");
			throw new RuntimeException("IOError writing file to output stream");
		}

	}
}
